<template>
  <div v-if="visible" class="project-list-modal">
    <div class="project-list-overlay" @click="handleClose"></div>
    <div class="project-list-content">
      <div class="project-list-header">
        <h3 v-if="viewMode==='list'">📋 项目映射配置</h3>
        <h3 v-else>📋 测试项配置：项目 {{ selectedProjectName || selectedProjectCode }}</h3>
        <div class="header-actions">
          <button v-if="viewMode==='list'" @click="showAddMappingForm" class="add-project-btn" title="添加项目映射"><span class="btn-icon">➕</span>添加映射</button>
          <button v-if="viewMode==='list'" @click="saveProjectListConfig" class="add-project-btn" title="保存配置"><span class="btn-icon">💾</span>保存配置</button>
          <template v-else>
            <button @click="showAddProductForm" class="add-project-btn" title="添加产品"><span class="btn-icon">➕</span>添加产品</button>
            <button @click="saveProjectListConfig" class="add-project-btn" title="保存配置"><span class="btn-icon">💾</span>保存配置</button>
            <button @click="backToList" class="add-project-btn" title="返回项目映射">返回</button>
          </template>
          <button @click="handleClose" class="close-modal-btn" title="关闭">✖️</button>
        </div>
      </div>

      <div class="project-list-table-container" v-if="viewMode==='list'">
        <table class="project-list-table">
          <thead>
            <tr>
              <th class="col-项目编号">项目编号</th>
              <th class="col-项目名称">项目名称</th>
              <th class="col-操作">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(project, index) in tempProjectList" :key="project.id" class="project-row">
              <td class="col-项目编号">{{ project.项目编号 }}</td>
              <td class="col-项目名称">{{ project.项目名称 }}</td>
              <td class="col-操作">
                <div class="row-actions">
                  <button @click="enterDetail(project.项目编号)" class="add-project-btn" title="配置产品测试项">配置产品测试项</button>
                  <button @click="deleteProject(project.id)" class="delete-project-btn" title="删除映射"><span class="btn-icon">✕</span></button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="project-list-table-container" v-else>
        <table class="project-list-table">
          <thead>
            <tr>
              <th class="col-产品名称">产品名称</th>
              <th v-for="testItem in testItemsConfig.filter(item => item.enabled)" :key="testItem.key" :class="`col-${testItem.key}`">{{ testItem.label }}</th>
              <th class="col-操作">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(product, index) in productsForSelected" :key="(product.产品名称 || '') + '-' + index" class="project-row">
              <td class="col-产品名称">{{ product.产品名称 }}</td>
              <td v-for="testItem in testItemsConfig.filter(item => item.enabled)" :key="testItem.key" :class="`col-${testItem.key} test-cell`" @click="toggleProductTestItem(index, testItem.key)">
                <div class="test-checkbox" :class="{ 'checked': product.测试项[testItem.key] }">
                  <span v-if="product.测试项[testItem.key]" class="checkmark">✓</span>
                </div>
              </td>
              <td class="col-操作">
                <button @click="deleteProduct(index)" class="delete-project-btn" title="删除产品"><span class="btn-icon">✕</span></button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- 添加项目映射模态，仅编号与名称 -->
  <div v-if="showAddMappingModal" class="add-project-modal">
    <div class="add-project-overlay" @click="closeAddProjectForm"></div>
    <div class="add-project-content">
      <div class="add-project-header">
        <h3>➕ 添加项目映射</h3>
        <button @click="closeAddProjectForm" class="close-modal-btn" title="关闭">✖️</button>
      </div>

      <div class="add-project-form">
        <div class="form-row">
          <div class="form-group">
            <label for="new-project-number">项目编号：</label>
            <input type="text" id="new-project-number" v-model="newProject.项目编号" placeholder="请输入项目编号" class="form-input" />
          </div>
          <div class="form-group">
            <label for="new-project-name">项目名称：</label>
            <input type="text" id="new-project-name" v-model="newProject.项目名称" placeholder="请输入项目名称" class="form-input" />
          </div>
        </div>
      </div>

      <div class="add-project-footer">
        <button @click="closeAddProjectForm" class="cancel-btn"><span class="btn-icon">✖️</span>取消</button>
        <button @click="addNewMapping" class="confirm-btn"><span class="btn-icon">✅</span>确认添加</button>
      </div>
    </div>
  </div>

  <!-- 添加产品模态，仅产品名称与测试项 -->
  <div v-if="showAddProductModal" class="add-project-modal">
    <div class="add-project-overlay" @click="closeAddProductForm"></div>
    <div class="add-project-content">
      <div class="add-project-header">
        <h3>➕ 添加产品（项目 {{ selectedProjectCode }}）</h3>
        <button @click="closeAddProductForm" class="close-modal-btn" title="关闭">✖️</button>
      </div>

      <div class="add-project-form">
        <div class="form-row">
          <div class="form-group">
            <label for="new-product-name">产品名称：</label>
            <input type="text" id="new-product-name" v-model="newProduct.产品名称" placeholder="请输入产品名称" class="form-input" />
          </div>
        </div>

        <div class="form-section">
          <h4>测试项配置：</h4>
          <div class="test-items-grid">
            <div v-for="testItem in testItemsConfig.filter(item => item.enabled)" :key="testItem.key" class="test-item-checkbox">
              <label class="checkbox-label">
                <input type="checkbox" v-model="newProduct.测试项[testItem.key]" class="checkbox-input" />
                <span class="checkbox-text">{{ testItem.label }}</span>
              </label>
            </div>
          </div>
        </div>
      </div>

      <div class="add-project-footer">
        <button @click="closeAddProductForm" class="cancel-btn"><span class="btn-icon">✖️</span>取消</button>
        <button @click="addNewProduct" class="confirm-btn"><span class="btn-icon">✅</span>确认添加</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue'
import { getProjects, saveProjects } from '@/api.js'
import userStore from '@/store/userStore.js'

export default {
  name: 'ProjectConfig',
  props: {
    visible: { type: Boolean, default: false }
  },
  setup(props, { emit }) {
    const projectList = ref([])
    const originalProjectList = ref([])
    const tempProjectList = ref([])
    const showAddMappingModal = ref(false)
    const showAddProductModal = ref(false)
    const viewMode = ref('list')
    const selectedProjectCode = ref('')

    const testItemsConfig = ref([
      { key: '耐压', label: '耐压', enabled: true },
      { key: '开门时间', label: '开门时间', enabled: true },
      { key: '关门时间', label: '关门时间', enabled: true },
      { key: '塞拉力', label: '塞拉力', enabled: true },
      { key: '推力', label: '推力', enabled: true },
      { key: '拉力', label: '拉力', enabled: true },
      { key: '软件版本', label: '软件版本', enabled: true }
    ])

    const createInitialNewProject = () => {
      const testItems = {}
      testItemsConfig.value.forEach(item => { testItems[item.key] = false })
      return { 项目编号: '', 项目名称: '', 产品名称: '', 测试项: testItems }
    }

    const newProject = ref(createInitialNewProject())
    const createInitialNewProduct = () => {
      const testItems = {}
      testItemsConfig.value.forEach(item => { testItems[item.key] = false })
      return { 产品名称: '', 测试项: testItems }
    }
    const newProduct = ref(createInitialNewProduct())

    const resetNewProject = () => { newProject.value = createInitialNewProject() }

    const fetchProjects = async () => {
      try {
        const response = await getProjects()
        if (response.success) {
          // 归一化为嵌套结构
          const data = response.data || []
          data.forEach(p => {
            if (!Array.isArray(p.产品)) {
              p.产品 = []
            }
            if (p.产品名称 || p.测试项) {
              const t = p.测试项 || {}
              p.产品.push({ 产品名称: p.产品名称 || '', 测试项: t })
              delete p.产品名称
              delete p.测试项
            }
          })
          projectList.value = data
          originalProjectList.value = JSON.parse(JSON.stringify(projectList.value))
          tempProjectList.value = JSON.parse(JSON.stringify(projectList.value))
        }
      } catch (e) {
        originalProjectList.value = JSON.parse(JSON.stringify(projectList.value))
        tempProjectList.value = JSON.parse(JSON.stringify(projectList.value))
      }
    }


    const productsForSelected = computed(() => {
      const proj = tempProjectList.value.find(p => p.项目编号 === selectedProjectCode.value)
      return proj && Array.isArray(proj.产品) ? proj.产品 : []
    })
    const selectedProjectName = computed(() => {
      const proj = tempProjectList.value.find(p => p.项目编号 === selectedProjectCode.value)
      return proj ? proj.项目名称 : ''
    })
    const toggleProductTestItem = (productIndex, testKey) => {
      const projIndex = tempProjectList.value.findIndex(p => p.项目编号 === selectedProjectCode.value)
      if (projIndex < 0) return
      const proj = tempProjectList.value[projIndex]
      const newProducts = (proj.产品 || []).map((p, i) => {
        if (i !== productIndex) return p
        const nextTests = { ...(p.测试项 || {}) }
        if (Object.prototype.hasOwnProperty.call(nextTests, testKey)) {
          nextTests[testKey] = !nextTests[testKey]
        }
        return { ...p, 测试项: nextTests }
      })
      const updatedProj = { ...proj, 产品: newProducts }
      tempProjectList.value = tempProjectList.value.map((p, i) => (i === projIndex ? updatedProj : p))
    }

    const saveProjectListConfig = async () => {
      try {
        projectList.value = JSON.parse(JSON.stringify(tempProjectList.value))
        const response = await saveProjects(projectList.value)
        if (response.success) {
          originalProjectList.value = JSON.parse(JSON.stringify(projectList.value))
        }
      } catch (e) {
        originalProjectList.value = JSON.parse(JSON.stringify(projectList.value))
      }
    }

    const cancelProjectListConfig = () => {
      tempProjectList.value = JSON.parse(JSON.stringify(originalProjectList.value))
      handleClose()
    }

    const showAddMappingForm = () => { resetNewProject(); showAddMappingModal.value = true }
    const showAddProductForm = () => { newProduct.value = createInitialNewProduct(); showAddProductModal.value = true }
    const closeAddProjectForm = () => {
      showAddMappingModal.value = false
    }
    const closeAddProductForm = () => {
      showAddProductModal.value = false
    }

    const addNewMapping = () => {
      const code = newProject.value.项目编号.trim()
      const name = newProject.value.项目名称.trim()
      if (!code) { alert('请输入项目编号'); return }
      if (!name) { alert('请输入项目名称'); return }
      const exists = tempProjectList.value.some(p => (p.项目编号 || '') === code)
      if (exists) { alert('项目编号已存在'); return }
      const maxId = Math.max(...tempProjectList.value.map(p => p.id || 0), 0)
      const newId = maxId + 1
      const newProjectData = { id: newId, 项目编号: code, 项目名称: name, 产品: [] }
      tempProjectList.value.push(newProjectData)
      closeAddProjectForm()
    }

    const addNewProduct = () => {
      const projCode = selectedProjectCode.value.trim()
      const prodName = newProduct.value.产品名称.trim()
      if (!projCode) { alert('请选择项目'); return }
      if (!prodName) { alert('请输入产品名称'); return }
      const projIndex = tempProjectList.value.findIndex(p => p.项目编号 === projCode)
      if (projIndex < 0) return
      const proj = tempProjectList.value[projIndex]
      const next = Array.isArray(proj.产品) ? [...proj.产品] : []
      const dup = next.some(p => (p.产品名称 || '') === prodName)
      if (dup) { alert('产品名称已存在'); return }
      next.push({ 产品名称: prodName, 测试项: { ...newProduct.value.测试项 } })
      const updatedProj = { ...proj, 产品: next }
      tempProjectList.value = tempProjectList.value.map((p, i) => (i === projIndex ? updatedProj : p))
      closeAddProductForm()
    }

    const deleteProject = (projectId) => {
      const project = tempProjectList.value.find(p => p.id === projectId)
      if (!project) return
      const confirmDelete = confirm(`确定要删除项目映射 "${project.项目编号} - ${project.项目名称}" 吗？此操作将在保存配置后生效。`)
      if (confirmDelete) {
        const index = tempProjectList.value.findIndex(p => p.id === projectId)
        if (index > -1) { tempProjectList.value.splice(index, 1) }
      }
    }

    const deleteProduct = (productIndex) => {
      const projIndex = tempProjectList.value.findIndex(p => p.项目编号 === selectedProjectCode.value)
      if (projIndex < 0) return
      const cloned = JSON.parse(JSON.stringify(tempProjectList.value))
      const proj = cloned[projIndex]
      if (!Array.isArray(proj.产品)) proj.产品 = []
      const target = proj.产品[productIndex]
      if (!target) return
      const confirmDelete = confirm(`确定要删除产品 "${target.产品名称}" 吗？此操作将在保存配置后生效。`)
      if (!confirmDelete) return
      proj.产品.splice(productIndex, 1)
      tempProjectList.value = cloned
    }

    const isDirty = computed(() => JSON.stringify(tempProjectList.value) !== JSON.stringify(originalProjectList.value))
    const handleClose = async () => {
      if (isDirty.value) {
        const confirmSave = confirm('存在未保存的更改。是否保存？')
        if (confirmSave) { await saveProjectListConfig() }
      }
      viewMode.value = 'list'
      selectedProjectCode.value = ''
      emit('close')
    }
    const enterDetail = (projectCode) => { selectedProjectCode.value = projectCode; viewMode.value = 'detail' }
    const backToList = () => { viewMode.value = 'list'; selectedProjectCode.value='' }

    watch(() => props.visible, async (val) => { if (val) { await fetchProjects(); const prefill = userStore.get('prefill_project_code'); if (prefill) { resetNewProject(); newProject.value.项目编号 = prefill; showAddMappingModal.value = true; userStore.set('prefill_project_code','') } } else { showAddMappingModal.value = false; showAddProductModal.value = false; viewMode.value='list'; selectedProjectCode.value='' } })

    return {
      projectList,
      originalProjectList,
      tempProjectList,
      testItemsConfig,
      showAddMappingModal,
      showAddProductModal,
      newProject,
      newProduct,
      viewMode,
      selectedProjectCode,
      selectedProjectName,
      productsForSelected,
      toggleProductTestItem,
      saveProjectListConfig,
      cancelProjectListConfig,
      showAddMappingForm,
      showAddProductForm,
      closeAddProjectForm,
      closeAddProductForm,
      addNewMapping,
      addNewProduct,
      deleteProduct,
      deleteProject,
      handleClose,
      enterDetail,
      backToList
    }
  }
}
</script>

<style scoped>
.project-list-modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; display: flex; align-items: center; justify-content: center; }
.project-list-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); backdrop-filter: blur(2px); }
.project-list-content { position: relative; width: 95%; height: calc(100vh - 140px); max-width: 1400px; background: white; border-radius: 12px; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3); display: flex; flex-direction: column; overflow: hidden; margin-top: 70px; }
.project-list-header { display: flex; justify-content: space-between; align-items: center; padding: 20px 30px; background-color: #f8f9fa; color: #495057; border-radius: 12px 12px 0 0; border-bottom: 1px solid #e9ecef; }
.project-list-header h3 { margin: 0; font-size: 24px; font-weight: 600; }
.close-modal-btn { background: transparent; color: #495057; border: none; width: 40px; height: 40px; border-radius: 50%; cursor: pointer; font-size: 18px; font-weight: bold; transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; }
.close-modal-btn:hover { background: rgba(0, 0, 0, 0.05); transform: scale(1.06); }
.project-list-table-container { flex: 1; overflow: auto; padding: 0; background: #f8f9fa; }
.project-list-table { width: 100%; border-collapse: collapse; background: white; font-size: 14px; }
.project-list-table th { background: linear-gradient(135deg, #e9ecef, #f8f9fa); color: #495057; font-weight: 600; padding: 12px 10px; text-align: center; border: 1px solid #dee2e6; position: sticky; top: 0; z-index: 10; white-space: nowrap; }
.project-list-table td { padding: 8px 10px; text-align: center; border: 1px solid #dee2e6; vertical-align: middle; white-space: nowrap; }
.project-row:nth-child(even) { background-color: #f8f9fa; }
.project-row:hover { background-color: #e3f2fd; }
.col-项目编号 { width: 180px; min-width: 180px; }
.col-项目名称 { width: 220px; min-width: 180px; }
.col-产品名称 { width: 160px; min-width: 140px; }
.col-耐压,.col-开门时间,.col-关门时间,.col-塞拉力,.col-推力,.col-拉力,.col-软件版本 { width: 100px; min-width: 100px; }
.test-cell { cursor: pointer; transition: all 0.2s ease; padding: 8px !important; }
.test-cell:hover { background-color: #e3f2fd !important; transform: scale(1.05); }
.test-checkbox { width: 24px; height: 24px; border: 2px solid #6c757d; border-radius: 4px; display: flex; align-items: center; justify-content: center; margin: 0 auto; transition: all 0.3s ease; background: white; }
.test-checkbox.checked { background: linear-gradient(135deg, #28a745, #20c997); border-color: #28a745; color: white; }
.checkmark { font-size: 16px; font-weight: bold; line-height: 1; }
.project-list-footer { padding: 20px 30px; background: linear-gradient(135deg, #f8f9fa, #ffffff); border-top: 1px solid #dee2e6; display: flex; justify-content: center; align-items: center; gap: 16px; border-radius: 0 0 12px 12px; }
.save-config-btn { display: flex; align-items: center; gap: 8px; padding: 12px 24px; background-color: #0d47a1; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 16px; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(13, 71, 161, 0.2); }
.save-config-btn:hover { background-color: #1976d2; transform: translateY(-2px); box-shadow: 0 6px 20px rgba(13, 71, 161, 0.3); }
.btn-icon { font-size: 14px; }
.header-actions { display: flex; align-items: center; gap: 12px; }
.add-project-btn { background-color: #0d47a1; color: white; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; display: flex; align-items: center; gap: 6px; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(13, 71, 161, 0.2); }
.add-project-btn:hover { background-color: #1976d2; transform: translateY(-1px); box-shadow: 0 4px 8px rgba(13, 71, 161, 0.3); }
.add-project-btn:active { transform: translateY(0); }
.delete-project-btn { background: linear-gradient(135deg, #f44336, #d32f2f); color: white; border: none; padding: 6px 10px; border-radius: 4px; cursor: pointer; font-size: 12px; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(244, 67, 54, 0.3); }
.delete-project-btn .btn-icon { color: white; font-weight: bold; font-size: 14px; }
.delete-project-btn:hover { background: linear-gradient(135deg, #d32f2f, #b71c1c); transform: translateY(-1px); box-shadow: 0 4px 8px rgba(244, 67, 54, 0.4); }
.delete-project-btn:active { transform: translateY(0); }
.col-操作 { width: 120px; text-align: center; }
.row-actions { display: flex; align-items: center; justify-content: center; gap: 4px; width: 100%; }
.add-project-modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1001; display: flex; align-items: center; justify-content: center; }
.add-project-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); }
.add-project-content { position: relative; background: white; border-radius: 12px; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3); width: 90%; max-width: 600px; max-height: 80vh; overflow: hidden; display: flex; flex-direction: column; }
.add-project-header { background-color: #f8f9fa; color: #495057; padding: 16px 20px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #e9ecef; }
.add-project-header h3 { margin: 0; font-size: 18px; font-weight: 600; }
.add-project-form { padding: 24px; overflow-y: auto; flex: 1; }
.form-row { display: flex; gap: 16px; margin-bottom: 20px; }
.form-group { flex: 1; display: flex; flex-direction: column; }
.form-group label { font-weight: 500; margin-bottom: 6px; color: #333; font-size: 14px; }
.form-input { padding: 10px 12px; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 14px; transition: all 0.3s ease; background: #fafafa; }
.form-input:focus { outline: none; border-color: #2196F3; background: white; box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1); }
.form-section { margin-top: 24px; }
.form-section h4 { margin: 0 0 16px 0; color: #333; font-size: 16px; font-weight: 600; }
.test-items-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
.test-item-checkbox { display: flex; align-items: center; }
.checkbox-label { display: flex; align-items: center; cursor: pointer; font-size: 14px; color: #555; transition: color 0.3s ease; }
.checkbox-label:hover { color: #2196F3; }
.checkbox-input { margin-right: 8px; width: 16px; height: 16px; cursor: pointer; }
.checkbox-text { user-select: none; }
.add-project-footer { background: #f8f9fa; padding: 16px 24px; display: flex; justify-content: flex-end; gap: 12px; border-top: 1px solid #e0e0e0; }
.cancel-btn { background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; display: flex; align-items: center; gap: 6px; transition: all 0.3s ease; }
.cancel-btn:hover { background: #5a6268; transform: translateY(-1px); }
.confirm-btn { background-color: #0d47a1; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; display: flex; align-items: center; gap: 6px; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(13, 71, 161, 0.2); }
.confirm-btn:hover { background-color: #1976d2; transform: translateY(-1px); box-shadow: 0 4px 8px rgba(13, 71, 161, 0.3); }

@media (max-width: 1200px) {
  .project-list-content { width: 98%; height: calc(100vh - 100px); margin-top: 50px; }
  .project-list-table { font-size: 13px; }
  .project-list-table th, .project-list-table td { padding: 10px 8px; }
}
@media (max-width: 768px) {
  .project-list-content { width: 100%; height: 100vh; margin-top: 0; border-radius: 0; }
  .project-list-header { padding: 15px 20px; border-radius: 0; }
  .project-list-header h3 { font-size: 20px; }
  .project-list-table { font-size: 12px; }
  .project-list-table th, .project-list-table td { padding: 8px 6px; }
  .col-序号, .col-项目编号, .col-项目名称, .col-产品名称, .col-耐压, .col-开门时间, .col-关门时间, .col-塞拉力, .col-推力, .col-拉力, .col-软件版本 { width: auto; min-width: 60px; }
  .test-checkbox { width: 20px; height: 20px; }
  .checkmark { font-size: 14px; }
}
</style>